﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

using CE.User;
using CE.Mail;
using CE.Image;
using CE.Company;
using CE.Global;

public partial class car_insurance_login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Customer))
            {
                //Response.Redirect("profile.aspx");
                //Response.Redirect("carAndpolicy_details.aspx");
                Response.Redirect("~/user/viewresulthistory.aspx");
            }
            else if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                Response.Redirect("~/provider/providerhome.aspx");
            }
        }

        if (!Page.IsPostBack)
        {

            if (Page.PreviousPage != null)
            {
                ContentPlaceHolder _ph = (ContentPlaceHolder)Page.PreviousPage.Master.FindControl("ContentPlaceHolder1");
                TextBox _txtExEmail = (TextBox)_ph.FindControl("txtExEmail");
                TextBox _txtExAuthCode = (TextBox)_ph.FindControl("txtExAuthCode");
                if (_txtExEmail != null && _txtExAuthCode != null)
                {
                    txtExEmail.Text = Server.HtmlEncode(_txtExEmail.Text);
                    txtExAuthCode.Text = Server.HtmlEncode(_txtExAuthCode.Text);
                    Page.Validate();
                    if (Page.IsValid)
                    {
                        AutoLogin(200);
                    }
                }
            }
            else if (Request.Params["e"] != null)
            {
                txtExEmail.Text = Request.Params["e"].ToString();
                divExErrorMessage.Visible = true;
                lblLoginMessage.Visible = true;
                lblLoginMessage.Text = "Welcome back! Please enter your password to retrieve and re-run your last quote!";
                lblLoginMessage.Font.Bold = true;
                lblLoginMessage.ForeColor = System.Drawing.Color.Green;
                if (Session[CE.Global.General.CI_RED] != null)
                {
                    lblRED.Text = Session[CE.Global.General.CI_RED].ToString();
                    //Response.Write(Session["CI_RED"].ToString());
                }

                if (Request.Params["rq"] != null && Request.Params["rq"].ToString() == "1")
                {
                    if (Request.Params["red"] != null)
                    {
                        string _reDate = Request.Params["red"].ToString();
                        try
                        {


                            int _intRedDate = 0;
                            if (_reDate.Length == 8 && int.TryParse(_reDate, out _intRedDate))
                            {
                                int _intRedDay = Convert.ToInt32(_reDate.Substring(0, 2));
                                int _intRedMonth = Convert.ToInt32(_reDate.Substring(2, 2));
                                int _intRedYear = Convert.ToInt32(_reDate.Substring(4, 4));

                                DateTime dtRed = new DateTime(_intRedYear, _intRedMonth, _intRedDay);
                                Session[CE.Global.General.CI_RED] = dtRed.ToString("dd/MMM/yyyy");
                                UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
                                _userviewdb.LogViewedCIREQuoteNowHistory("CIRE", Request, txtExEmail.Text, Session[CE.Global.General.CI_RED].ToString());
                                Response.Redirect("login.aspx?e=" + Request.Params["e"].ToString());
                            }
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }

            CE.Provider.InsurerDB _insurerdb = new CE.Provider.InsurerDB();

            LogUserViewedHistory();

            txtExEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtExEmail.ClientID + "','" + rfvExEmail.ClientID + "','" + rfvExEmailValid.ClientID + "')");
            txtExAuthCode.Attributes.Add("onblur", "ShowValidationEffect('" + txtExAuthCode.ClientID + "','" + rfvExAuthCode.ClientID + "')");

        }
    }

    protected void ibtLogin_Click(object sender, ImageClickEventArgs e)
    {
        #region Existing Customer
        if (Page.IsValid)
        {
            AutoLogin(100);
        }
        #endregion

    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        #region Existing Customer
        if (Page.IsValid)
        {
            AutoLogin(100);
        }
        #endregion

    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("USR", Request, "User login & register.");
    }

    private void AutoLogin(int LoginType)
    {
        AccountStatus _accountstatus = new AccountStatus();
        AccountStatusDB _accountstatusdb = new AccountStatusDB();
        AccountDB _accountdb = new AccountDB();
        //Check Customer Account 
        Account _account = _accountdb.GetUserAccount(txtExEmail.Text.ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));

        if (_account != null)
        {
            if (CheckUserLoginCached(_account.CEID.ToString()))
            {
                _accountstatus = _accountstatusdb.GetAccountStatus(_account.CEID, 400);


                if (Server.HtmlDecode(txtExAuthCode.Text) == _account.AuthCode)
                {
                    if (_account.Status == true)
                    {
                        if (_account.Info1 == "0")
                        {
                            //Reset Email Fail Message
                            _account.Info1 = "";
                            _account.Info2 = "";
                            _accountdb.Insert(_account);
                        }

                        _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                        divExErrorMessage.Visible = false;
                        GetUserInformation(_account);
                        SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                        CE.Global.General.CreateUpdateUserLoginCached(Page);
                        _account = null;
                        if (LoginType == 100)
                        {
                            //Response.Redirect("profile.aspx");
                            //Response.Redirect("carAndpolicy_details.aspx");

                            Response.Redirect("~/user/viewresulthistory.aspx");
                        }
                        else
                        {
                            if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
                                Response.Redirect("~/user/viewresulthistory.aspx");
                            else
                            {
                                Response.Redirect("~/user/editprofile.aspx");
                            }
                        }
                    }
                    else
                    {
                        lblLoginMessage.Text = "Your email has been blocked!";
                    }
                }
                else
                {
                    divExErrorMessage.Visible = true;
                    _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 0);
                    lblLoginMessage.Text = "Email address or password is incorrect.";
                }
            }
            else
            {
                //Response.Redirect("UserMessage.aspx?ErrorCode=1993");
                Response.Redirect("~/User/UserMessage.aspx?mt=UM&ec=1993");
            }
        }
        else
        {
            divExErrorMessage.Visible = true;
            lblLoginMessage.Text = "Email address or password is incorrect.";
        }

        lblLoginMessage.ForeColor = System.Drawing.Color.Red;
    }

    private bool CheckUserLoginCached(string UserId)
    {
        bool _retValue = false;
        string sKey = CE.Configuration.MyConfigurationManager.GetAppSettingValue("UserCacheName");
        sKey += UserId;
        if (HttpContext.Current.Cache[sKey] == null)
        {
            _retValue = true;
        }
        else
        {
            _retValue = false;
        }
        return _retValue;
    }

    private bool SendMailToUser(string DummyAuthCode)
    {
        bool _retVal = false;
        //MyMailManager _mailMgr = new MyMailManager();

        string _mailBody = "";
        string _currentDomainUrl = "http://" + HttpContext.Current.Request.Url.Host.ToString();
        string imgLogoUrl = _currentDomainUrl + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
        CompanyInformation _company = new CompanyInformation();
        CompanyInformationDB _companydb = new CompanyInformationDB();
        _company = _companydb.GetCompanyInformation(3);
        string _companyAddress = "";
        string _emailaddress = "";
        string _websiteaddress = "";
        if (_company != null)
        {
            _companyAddress = _company.Address1;
            _emailaddress = _company.EmailAddress;
            _websiteaddress = _company.Website;
        }
        _company = null;
        _companydb = null;

        _mailBody = "Dear " + Session[CE.Global.General.UserName].ToString() + ", <br /><br />Your account has been created — now it will be easier to compare and find the best car insurance.";
        _mailBody += "<br /><br />You may now log in to <a href='http://www.comparexpress.com/car-insurance' target='_blank'>http://www.comparexpress.com/car-insurance</a> using the following username and password:";
        _mailBody += "<br /><br /> User Name : " + txtExEmail.Text;
        _mailBody += "<br /> Password : " + DummyAuthCode;
        _mailBody += "<br /><br />If you have any questions, comments, or feedback, please do not hesitate to contact us at <a href='mailto:support@comparexpress.com'>support@comparexpress.com</a>.";
        _mailBody += "<br /><br />Best Regards,<br /><br />Your CompareXpress Team<br/>Customer Support - SG/International";
        _mailBody += "<br /><img src='" + imgLogoUrl + "' />";
        _mailBody += "<br /><hr />";
        _mailBody += _companyAddress;
        _mailBody += "<br /><a href='" + _websiteaddress + "' target='_blank'>" + _websiteaddress + "</a> :: <a href='mailto:" + _emailaddress + "' target='_blank'>" + _emailaddress + "</a><br /><hr />";
        _mailBody += "<br /><i>This is a computer-generated email. Please do not reply to this email.</i>";

        if (MyMailManager.SendCRMMessage(txtExEmail.Text, "Welcome to CompareXpress", _mailBody))
        {
            _retVal = true;
        }
        else
        {
            _retVal = false;
        }

        return _retVal;
    }

    private void GetUserInformation(Account _account)
    {
        DateTime dtNow = new DateTime();
        dtNow = CE.Global.General.GetUTCDateTime();
        Session[CE.Global.General.UserId] = _account.CEID;
        Session[CE.Global.General.UserTypeId] = _account.UserTypeId;

        if (_account.UserTypeId == Convert.ToInt32(CE.Global.CEUserType.Provider))
        {
            CE.Provider.ProviderCompanyLink _comlink = new CE.Provider.ProviderCompanyLink();
            CE.Provider.ProviderCompanyLinkDB _comlinkdb = new CE.Provider.ProviderCompanyLinkDB();
            _comlink = _comlinkdb.GetProviderCompanyId(_account.CEID);
            if (_comlink != null)
            {
                Session[CE.Global.General.ProviderCompanyId] = _comlink.ProviderCompanyId;
            }
        }

        Session[CE.Global.General.UserEmail] = _account.Email;
        Session[CE.Global.General.StartTime] = dtNow.ToString();
        bool isProfileComplete = false;
        bool isContactComplete = false;

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        _contact = _contactdb.GetContact(_account.CEID);

        _profile = _profiledb.GetProfile(_account.CEID);

        if (_contact != null)
        {
            isContactComplete = true;
            Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
        }
        else
        {
            Session[CE.Global.General.UserPhoneNo] = null;
        }

        if (_profile != null)
        {
            if (_profile.FirstName != null && _profile.FirstName != string.Empty)
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName) + " " + Server.HtmlDecode(_profile.FirstName);
            }
            else
            {
                Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
            }

            if (!string.IsNullOrEmpty(_profile.IDType) &&
                !string.IsNullOrEmpty(_profile.IDNo) &&
                _profile.IDNo.Length == 9)
            {
                Session[CE.Global.General.UserICNumber] = _profile.IDType + " " + _profile.IDNo;
            }

            if (_profile.Status.ToLower() == "complete")
            {
                isProfileComplete = true;
            }
            else
            {
                isProfileComplete = false;
            }
        }
        else
        {
            Session[CE.Global.General.UserName] = null;
        }

        if (isProfileComplete && isContactComplete)
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "1";
        }
        else
        {
            Session[CE.Global.General.UserProfileAndContactComplete] = "0";
        }

    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = CE.Global.General.GetUTCDateTime();
        _loghis.EndTime = CE.Global.General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;

            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;

            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            if (Session["CI_RED"] != null)
            {
                _loginfo.Info1 = Session[CE.Global.General.CI_RED].ToString();
            }
            //_loginfo.Info1 = Request.Browser.Tables;
            //_loginfo.Info2 = Request.Browser.Platform;
            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    protected void btnFBLogin_Click(object sender, EventArgs e)
    {
        string[] _fbdata = hiddenData.Value.Split(';');

        Account _useraccount = new Account();
        AccountDB _useraccountdb = new AccountDB();

        if (_useraccountdb.IsAlreadyExist(_fbdata[0], Convert.ToInt32(CE.Global.CEUserType.Customer)))
        {
            if (_fbdata[0] != null)
            {
                if (_fbdata[0].Length > 0)
                {
                    //lblAutoKey.Text = Request.Params["authkey"].ToString();
                    //lblGUID.Text = Request.Params["uid"].ToString();
                    ViewState["UID"] = _fbdata[0];
                    Account _account = new Account();
                    AccountDB _accountdb = new AccountDB();
                    _account = _accountdb.GetUserAccount(_fbdata[0], Convert.ToInt32(CE.Global.CEUserType.Customer));

                    int LoginType = 100;
                    AccountStatus _accountstatus = new AccountStatus();
                    AccountStatusDB _accountstatusdb = new AccountStatusDB();
                    if (_account != null)
                    {
                        if (_account.Status == true)
                        {
                            if (_account.Info1 == "0")
                            {
                                //Reset Email Fail Message
                                _account.Info1 = "";
                                _account.Info2 = "";
                                _accountdb.Insert(_account);
                            }

                            _accountstatusdb.InsertAccountStatus(_account.CEID, 400, 1);
                            GetUserInformation(_account);
                            SaveUserLoginInformation(_account.CEID, _account.UserTypeId);
                            CE.Global.General.CreateUpdateUserLoginCached(Page);
                            _account = null;
                            if (LoginType == 100)
                            {
                                //Response.Redirect("profile.aspx");
                                //Response.Redirect("carAndpolicy_details.aspx");

                                Response.Redirect("~/user/viewresulthistory.aspx");
                            }
                            else
                            {
                                if (Session[CE.Global.General.UserProfileAndContactComplete].ToString() == "1")
                                    Response.Redirect("~/user/viewresulthistory.aspx");
                                else
                                {
                                    Response.Redirect("~/user/editprofile.aspx");
                                }
                            }
                        }
                        else
                        {
                            Response.Redirect("~/car-insurance/login.aspx");
                        }

                    }
                    else
                    {
                        Response.Redirect("~/car-insurance/login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("~/car-insurance/login.aspx");
                }
            }
            else
            {
                Response.Redirect("~/car-insurance/login.aspx");
            }
        }
        else
        {
            RegisterUser();
        }
    }

    private void RegisterUser()
    {
        string[] _fbdata = hiddenData.Value.Split(';');

        Account _useraccount = new Account();
        AccountDB _useraccountdb = new AccountDB();

        Profile _userprofile = new Profile();
        ProfileDB _userprofiledb = new ProfileDB();
        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        long _result = -1;

        _useraccount.Email = _fbdata[0];

        Random _random = new Random();
        string _authcode = "";
        //Sakthi on 21 Jan 2011
        //_authcode = "C" + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();
        _authcode = _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString() + _random.Next(9).ToString();

        _useraccount.AuthCode = _authcode;

        _useraccount.UserId = "CEUSERAUTOIDCI";
        _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
        _useraccount.IsAcceptTC = true;
        _useraccount.Status = true;
        if (Session[General.AgentId] != null)
        {
            //For Agent Create User - Phyo @28/Apr/2011
            _useraccount.RefCEUserID = Convert.ToInt64(Session[General.AgentId]);
        }
        else
        {
            _useraccount.RefCEUserID = -1;
        }
        _result = _useraccountdb.Insert(_useraccount);
        _useraccount.CEID = _result;

        if (_result > 0)
        {
            //_userprofile.Salutation = ddlSalutation.GetSalutation();

            _userprofile.FirstName = Server.HtmlEncode(_fbdata[1].ToUpper());
            _userprofile.SurName = Server.HtmlEncode(_fbdata[2].ToUpper());

            string[] _fbDOB = _fbdata[4].Split('/');
            DateTime _dtDOB = new DateTime(Int32.Parse(_fbDOB[2]), Int32.Parse(_fbDOB[0]), Int32.Parse(_fbDOB[1]));
            _userprofile.DOB = _dtDOB;

            char _fbgender = 'M';
            switch (_fbdata[3].ToLower())
            {
                case "male":
                    _fbgender = 'M';
                    break;
                case "female":
                    _fbgender = 'F';
                    break;
            }
            _userprofile.Gender = _fbgender;

            int _fbrelationship = 1;
            switch (_fbdata[5].ToLower())
            {
                case "single":
                    _fbrelationship = 1;
                    break;
                case "married":
                    _fbrelationship = 2;
                    break;
                case "widowed":
                    _fbrelationship = 4;
                    break;
                case "divorced":
                    _fbrelationship = 5;
                    break;
            }
            _userprofile.MaritalStatus = _fbrelationship;
            _userprofile.JobNature = "-1";
            _userprofile.Occupation = -1;
            _userprofile.YearDriveSg = 0;
            _userprofile.Status = "Complete";
            _userprofile.RefCEUserId = _useraccount.CEID;
            _result = _userprofiledb.Insert(_userprofile);

            _contact.Email = _useraccount.Email;
            _contact.Mobile = "";

            _contact.Status = true;
            _contact.RefCEUserId = _useraccount.CEID;
            _result = _contactdb.Insert(_contact);

            if (_result > 0)
            {
                SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
                Session[CE.Global.General.UserId] = _useraccount.CEID;
                Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                Session[CE.Global.General.UserEmail] = _useraccount.Email;
                Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                Session[CE.Global.General.StartTime] = CE.Global.General.GetUTCDateTime().ToString();
                if (_userprofile.FirstName != string.Empty)
                {
                    Session[CE.Global.General.UserName] = _userprofile.SurName + " " + _userprofile.FirstName;
                }
                else
                {
                    Session[CE.Global.General.UserName] = _userprofile.SurName;
                }

                ////update CarIds
                //Int64 _userId = Convert.ToInt64(Session[General.UserId].ToString());
                //Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());

                //CarDetailDB cardb = new CarDetailDB();
                //cardb.UpdateCarDetailPolicy(_carId, _userId);

                //Session[CE.Global.General.UserProfileAndContactComplete] = "1";

                //START Stop Welcome message @ 20/Dec/2011 - PHYO
                //string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IsCXLive");
                //if (_strCXLive != "")
                //{
                //    if (!SendMailToUser(_authcode))
                //    {
                //        //Email Can't be sent
                //        _useraccount.Info1 = "0";
                //        _useraccount.Info2 = "New User - Car Insurance";
                //        _result = _useraccountdb.Insert(_useraccount);

                //    }
                //}
                //END Stop Welcome message @ 20/Dec/2011 - PHYO

                //Response.Redirect("results.aspx?sortby=" + ddlSortBy.Text);
                Response.Redirect("~/user/viewresulthistory.aspx");
                //Response.Redirect("results-new.aspx?sortby=0");

            }
        }
    }
}
